package com.ruoyi.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.patrol.domain.PatrolPlan;
import com.ruoyi.patrol.domain.PatrolTask;
import com.ruoyi.patrol.mapper.PatrolTaskMapper;
import com.ruoyi.patrol.service.IPatrolPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component("patrolJob")
public class PatrolJob {

    @Autowired
    private IPatrolPlanService patrolPlanService;
    @Autowired
    private PatrolTaskMapper patrolTaskMapper;

    /**
     * 定时生成巡查任务
     */
    @Scheduled(cron = "2 2 0 * * ?")
    public void genTask(){
        PatrolPlan pc = new PatrolPlan();
        pc.setStatus("1");
        List<PatrolPlan> planList = patrolPlanService.selectPatrolPlanList(pc);
        if(StringUtils.isEmpty(planList)){
            return;
        }

        Date d = new Date();
        Date patrolDate = DateUtils.parseDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, d));
        PatrolTask tc = new PatrolTask();
        for(PatrolPlan patrolPlan:planList){
            //已经结束
            if(patrolPlan.getEndDate().before(d)){
                patrolPlan.setStatus("0");
                patrolPlanService.updatePatrolPlan(patrolPlan);
                continue;
            }

            tc.setPathId(patrolPlan.getPathId());
            if(patrolPlan.getCycle().equalsIgnoreCase("1")){
                tc.setPatrolDate(patrolDate);
                List<PatrolTask> old = patrolTaskMapper.selectPatrolTaskList(tc);
                if(StringUtils.isEmpty(old)){
                    createTask(patrolPlan, patrolDate);
                }
            }
        }
    }

    /**
     * 创建任务
     * @param patrolPlan
     * @param patrolDate
     */
    private void createTask(PatrolPlan patrolPlan, Date patrolDate){
        PatrolTask patrolTask = new PatrolTask();
        BeanUtils.copyBeanProp(patrolTask, patrolPlan);
        patrolTask.setId(null);
        patrolTask.setPatrolDate(patrolDate);
        patrolTask.setUpdateBy(null);
        patrolTask.setUpdateTime(null);
        patrolTask.setProgress("0");
        patrolTaskMapper.insertPatrolTask(patrolTask);
    }
}
